$(document).ready(function() {
    // 游戏配置项
    const gameConfig = {
        // 默认AI设置
        defaultAISettings: {
            proxyUrl: 'xxxx',
            apiKey: 'sk-xxxx',
            model: 'gpt-4-turbo'
        }
    };

    // 游戏状态
    const gameState = {
        phase: '准备阶段', // 准备阶段, 夜晚, 白天, 投票阶段, 结束
        nightSubPhase: null, // 天黑请闭眼, 狼人行动, 预言家行动, 女巫行动, 猎人行动
        daySubPhase: null, // 天亮, 玩家发言
        players: [],
        currentPlayer: null,
        votes: {},
        werewolves: [],
        seer: null,
        witch: null,
        hunter: null,
        prophet: null,
        deadPlayers: [],
        dayCount: 1,
        nightCount: 1,
        gameStarted: false,
        currentRole: null,
        currentActionPlayer: null,
        isGodMode: false, // 是否是上帝玩家模式
        playerAISettings: {}, // 存储每个玩家的AI设置
        witchPotions: {
            hasAntidote: true, // 女巫是否有解药
            hasPoison: true // 女巫是否有毒药
        },
        werewolfTargetVotes: {}, // 存储每个狼人选择的目标
        werewolfActions: {}, // 存储每个狼人是否已执行行动
        pendingDeathPlayer: null // 预死亡状态的玩家
    };
    
    // 狼人对话历史列表 - 专门用于保存狼人相关的对话和上下文
    let werewolfDialogues = [];
    
    // 角色配置
    const roles = {
        狼人: {
            icon: '🐺',
            description: '你是一名狼人，每晚可以与其他狼人一起杀死一名玩家。白天你需要隐藏身份，误导好人。',
            team: '狼人'
        },
        村民: {
            icon: '👤',
            description: '你是一名普通村民，没有特殊能力。白天你可以参与讨论并投票选出你认为是狼人的玩家。',
            team: '好人'
        },
        预言家: {
            icon: '🔮',
            description: '你是预言家，每晚可以查验一名玩家的身份。白天你可以选择是否公布查验结果。',
            team: '好人'
        },
        女巫: {
            icon: '🧙‍♀️',
            description: '你是女巫，拥有一瓶解药和一瓶毒药。解药可以救被狼人杀死的玩家，毒药可以毒死任意一名玩家。每局游戏只能使用每种药各一次。',
            team: '好人'
        },
        猎人: {
            icon: '🏹',
            description: '你是猎人，当你被狼人杀死或被投票出局时，可以开枪带走一名玩家。',
            team: '好人'
        }
    };
    
    // 初始化玩家
    function initPlayers() {
        // 询问用户是否是上帝玩家
        if (confirm('是否以上帝玩家身份开始游戏？（上帝玩家可以看到所有玩家的身份且不会被分配身份）')) {
            gameState.isGodMode = true;
            
            // 模拟8名玩家
            const playerNames = ['玩家1', '玩家2', '玩家3', '玩家4', '玩家5', '玩家6', '玩家7', '玩家8'];
            
            // 分配角色 (2狼人，1预言家，1女巫，1猎人，3村民)
            const roleDistribution = ['狼人', '狼人', '预言家', '女巫', '猎人', '村民', '村民', '村民']
            
            // 打乱角色顺序
            for (let i = roleDistribution.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [roleDistribution[i], roleDistribution[j]] = [roleDistribution[j], roleDistribution[i]];
            }
            
            // 创建玩家对象
            gameState.players = playerNames.map((name, index) => {
                const role = roleDistribution[index];
                const playerId = index + 1;
                const player = {
                    id: playerId,
                    name: name,
                    role: role,
                    status: '存活',
                    avatar: getAvatarForPlayer(name)
                };
                
                // 记录特殊角色
                if (role === '狼人') {
                    gameState.werewolves.push(playerId);
                } else if (role === '预言家') {
                    gameState.prophet = playerId;
                } else if (role === '女巫') {
                    gameState.witch = playerId;
                } else if (role === '猎人') {
                    gameState.hunter = playerId;
                }
                
                // 设置默认AI设置
                gameState.playerAISettings[playerId] = {
                    proxyUrl: gameConfig.defaultAISettings.proxyUrl,
                    apiKey: gameConfig.defaultAISettings.apiKey,
                    model: gameConfig.defaultAISettings.model
                };
                
                return player;
            });
            
            // 上帝玩家不分配身份
            gameState.currentPlayer = null;
            gameState.currentRole = null;
        } else {
            // 普通玩家模式
            // 模拟8名玩家
            const playerNames = ['玩家1', '玩家2', '玩家3', '玩家4', '玩家5', '玩家6', '玩家7', '玩家8'];
            
            // 分配角色 (2狼人，1预言家，1女巫，1猎人，3村民)
            const roleDistribution = ['狼人', '狼人', '预言家', '女巫', '猎人', '村民', '村民', '村民']
            
            // 打乱角色顺序
            for (let i = roleDistribution.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [roleDistribution[i], roleDistribution[j]] = [roleDistribution[j], roleDistribution[i]];
            }
            
            // 创建玩家对象
            gameState.players = playerNames.map((name, index) => {
                const role = roleDistribution[index];
                const player = {
                    id: index + 1,
                    name: name,
                    role: role,
                    status: '存活',
                    avatar: getAvatarForPlayer(name)
                };
                
                // 记录特殊角色
                if (role === '狼人') {
                    gameState.werewolves.push(player.id);
                } else if (role === '预言家') {
                    gameState.prophet = player.id;
                } else if (role === '女巫') {
                    gameState.witch = player.id;
                } else if (role === '猎人') {
                    gameState.hunter = player.id;
                }
                
                return player;
            });
            
            // 假设当前玩家是第一个
            gameState.currentPlayer = gameState.players[0];
            gameState.currentRole = gameState.currentPlayer.role;
        }
    }
    
    // 根据玩家名生成头像
    function getAvatarForPlayer(name) {
        const avatars = ['👨‍💼', '👩‍💼', '👨‍🔧', '👩‍🔧', '👨‍🎓', '👩‍🎓', '👨‍🏫', '👩‍🏫', '👨‍🚀', '👩‍🚀', '👨‍⚕️', '👩‍⚕️'];
        const index = name.charCodeAt(2) % avatars.length;
        return avatars[index];
    }
    
    // 渲染玩家卡片
    function renderPlayers() {
        const container = $('#players-container');
        container.empty();
        
        gameState.players.forEach(player => {
            const isDead = gameState.deadPlayers.includes(player.id);
            const cardClass = isDead ? 'player-card dead' : 'player-card';
            
            const card = $('<div>')
                .addClass(cardClass)
                .attr('data-id', player.id)
                .append($('<div>').addClass('player-avatar').text(player.avatar))
                .append($('<div>').addClass('player-name').text(player.name))
                .append($('<div>').addClass('player-status').text(player.status));
                
                // 上帝模式下显示所有玩家的身份
                if (gameState.isGodMode) {
                    const roleInfo = roles[player.role];
                    card.append($('<div>').addClass('player-role').text(`身份: ${player.role} ${roleInfo.icon}`));
                }
                
                // 添加信息图标（左上角）
                const infoIcon = $('<div>')
                    .addClass('player-info')
                    .text('ℹ️')
                    .click(function(e) {
                        // 阻止事件冒泡，避免触发玩家卡片的点击事件
                        e.stopPropagation();
                        showPlayerInfo(player.id);
                    });
                
                // 添加设置图标
                const settingsIcon = $('<div>')
                    .addClass('player-settings')
                    .text('⚙️')
                    .click(function(e) {
                        // 阻止事件冒泡，避免触发玩家卡片的点击事件
                        e.stopPropagation();
                        openPlayerAISettings(player.id);
                    });
                
                card.append(infoIcon);
                card.append(settingsIcon);
                
                // 点击玩家卡片的事件
                card.click(function() {
                    handlePlayerClick(player.id);
                });
                
                container.append(card);
        });
    }
    
    // 打开玩家AI设置对话框
    function openPlayerAISettings(playerId) {
        const player = getPlayerById(playerId);
        // 获取该玩家已有的AI设置
        const existingSettings = gameState.playerAISettings[playerId] || {
            proxyUrl: '',
            apiKey: '',
            model: 'gpt-4'
        };
        
        // 默认模型列表，作为后备选项
        const defaultModels = [
            { value: 'gpt-4-turbo', label: 'GPT-4' },
            { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' },
            { value: 'Deepseek-v3', label: 'Deepseek-v3' },
            { value: 'claude-3-sonnet-20240229', label: 'Claude 3 Sonnet' },
            { value: 'gemini-pro', label: 'Gemini Pro' }
        ];
        
        // 生成默认模型选项HTML
        const defaultModelOptions = defaultModels.map(model => 
            `<option value="${model.value}" ${existingSettings.model === model.value ? 'selected' : ''}>${model.label}</option>`
        ).join('');
        
        // 创建设置对话框HTML
        const dialogHtml = `
            <div style="
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.7);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 1000;
            ">
                <div style="
                    background: linear-gradient(135deg, #2a2a2a 0%, #1a1a1a 100%);
                    border-radius: 15px;
                    padding: 30px;
                    width: 90%;
                    max-width: 500px;
                    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
                ">
                    <h2 style="
                        color: #4ecdc4;
                        text-align: center;
                        margin-bottom: 20px;
                        font-size: 1.8rem;
                    ">
                        设置 ${player.name} 的AI参数
                    </h2>
                    
                    <div style="margin-bottom: 20px;">
                        <label style="
                            display: block;
                            color: #fff;
                            margin-bottom: 8px;
                            font-weight: bold;
                        ">
                            AI代理地址:
                        </label>
                        <input 
                            type="text" 
                            id="proxy-url" 
                            value="${existingSettings.proxyUrl}"
                            placeholder="例如: http://localhost:3000/v1"
                            style="
                                width: 100%;
                                padding: 10px;
                                border: 2px solid #4a4a4a;
                                border-radius: 5px;
                                background-color: #3a3a3a;
                                color: #fff;
                                font-size: 1rem;
                            "
                        />
                    </div>
                    
                    <div style="margin-bottom: 20px;">
                        <label style="
                            display: block;
                            color: #fff;
                            margin-bottom: 8px;
                            font-weight: bold;
                        ">
                            API Key:
                        </label>
                        <input 
                            type="password" 
                            id="api-key" 
                            value="${existingSettings.apiKey}"
                            placeholder="sk-..."
                            style="
                                width: 100%;
                                padding: 10px;
                                border: 2px solid #4a4a4a;
                                border-radius: 5px;
                                background-color: #3a3a3a;
                                color: #fff;
                                font-size: 1rem;
                            "
                        />
                    </div>
                    
                    <div style="margin-bottom: 30px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                            <label style="
                                display: block;
                                color: #fff;
                                font-weight: bold;
                            ">
                                对话大模型:
                            </label>
                            <button 
                                id="refresh-models"
                                style="
                                    padding: 5px 15px;
                                    background: #4a4a4a;
                                    color: #fff;
                                    border: none;
                                    border-radius: 20px;
                                    font-size: 0.8rem;
                                    cursor: pointer;
                                    transition: all 0.3s ease;
                                "
                            >
                                刷新模型列表
                            </button>
                        </div>
                        <select 
                            id="model-select"
                            style="
                                width: 100%;
                                padding: 10px;
                                border: 2px solid #4a4a4a;
                                border-radius: 5px;
                                background-color: #3a3a3a;
                                color: #fff;
                                font-size: 1rem;
                            "
                        >
                            ${defaultModelOptions}
                        </select>
                        <div id="model-status" style="
                            margin-top: 5px;
                            font-size: 0.8rem;
                            color: #666;
                            text-align: right;
                        ">
                            使用默认模型列表
                        </div>
                    </div>
                    
                    <div style="display: flex; gap: 15px; justify-content: center;">
                        <button 
                            id="save-settings"
                            style="
                                padding: 10px 30px;
                                background: linear-gradient(135deg, #4ecdc4, #45b7aa);
                                color: #fff;
                                border: none;
                                border-radius: 30px;
                                font-size: 1rem;
                                font-weight: bold;
                                cursor: pointer;
                                transition: all 0.3s ease;
                            "
                        >
                            保存设置
                        </button>
                        <button 
                            id="cancel-settings"
                            style="
                                padding: 10px 30px;
                                background: #666;
                                color: #fff;
                                border: none;
                                border-radius: 30px;
                                font-size: 1rem;
                                font-weight: bold;
                                cursor: pointer;
                                transition: all 0.3s ease;
                            "
                        >
                            取消
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        // 创建对话框元素
        const dialog = $(dialogHtml);
        $('body').append(dialog);
        
        // 刷新模型列表函数
        function refreshModelList() {
            const proxyUrl = dialog.find('#proxy-url').val().trim();
            const apiKey = dialog.find('#api-key').val().trim();
            const modelSelect = dialog.find('#model-select');
            const modelStatus = dialog.find('#model-status');
            
            if (!proxyUrl) {
                modelStatus.text('请先输入代理地址');
                modelStatus.css('color', '#ff6b6b');
                return;
            }
            
            // 显示加载状态
            modelStatus.text('正在加载模型列表...');
            modelStatus.css('color', '#4ecdc4');
            modelSelect.prop('disabled', true);
            
            // 构建获取模型列表的URL
            let modelsUrl = proxyUrl;
            if (!modelsUrl.endsWith('/')) {
                modelsUrl += '/';
            }
            modelsUrl += 'v1/models';
            
            // 发送请求获取模型列表
            $.ajax({
                url: modelsUrl,
                type: 'GET',
                headers: {
                    'Authorization': `Bearer ${apiKey}`
                },
                timeout: 10000, // 10秒超时
                success: function(response) {
                    // 尝试解析不同格式的响应
                    let models = [];
                    
                    // 检查是否是标准OpenAI格式
                    if (response.data && Array.isArray(response.data)) {
                        models = response.data.map(model => ({
                            value: model.id,
                            label: model.id
                        }));
                    }
                    // 检查是否是直接的模型数组
                    else if (Array.isArray(response)) {
                        models = response.map(model => ({
                            value: typeof model === 'string' ? model : model.id || model.value,
                            label: typeof model === 'string' ? model : model.name || model.label || (model.id || model.value)
                        }));
                    }
                    
                    if (models.length > 0) {
                        // 清空并填充新的模型选项
                        modelSelect.empty();
                        models.forEach(model => {
                            const option = $('<option>').val(model.value).text(model.label);
                            if (model.value === existingSettings.model) {
                                option.prop('selected', true);
                            }
                            modelSelect.append(option);
                        });
                        
                        modelStatus.text(`从代理获取到 ${models.length} 个模型`);
                        modelStatus.css('color', '#4ecdc4');
                    } else {
                        // 如果没有获取到模型，使用默认模型
                        modelSelect.empty();
                        defaultModels.forEach(model => {
                            const option = $('<option>').val(model.value).text(model.label);
                            if (model.value === existingSettings.model) {
                                option.prop('selected', true);
                            }
                            modelSelect.append(option);
                        });
                        
                        modelStatus.text('未获取到有效模型，使用默认列表');
                        modelStatus.css('color', '#ffd166');
                    }
                },
                error: function(xhr, status, error) {
                    // 请求失败，使用默认模型
                    modelSelect.empty();
                    defaultModels.forEach(model => {
                        const option = $('<option>').val(model.value).text(model.label);
                        if (model.value === existingSettings.model) {
                            option.prop('selected', true);
                        }
                        modelSelect.append(option);
                    });
                    
                    modelStatus.text(`获取模型失败: ${error || status}`);
                    modelStatus.css('color', '#ff6b6b');
                },
                complete: function() {
                    // 恢复选择框状态
                    modelSelect.prop('disabled', false);
                }
            });
        }
        
        // 绑定刷新模型列表按钮事件
        dialog.find('#refresh-models').click(refreshModelList);
        
        // 保存设置按钮点击事件
        dialog.find('#save-settings').click(function() {
            const proxyUrl = dialog.find('#proxy-url').val().trim();
            const apiKey = dialog.find('#api-key').val().trim();
            const model = dialog.find('#model-select').val();
            
            // 保存设置到gameState
            gameState.playerAISettings[playerId] = {
                proxyUrl: proxyUrl,
                apiKey: apiKey,
                model: model
            };
            
            // 显示保存成功提示
            alert(`${player.name} 的AI设置已保存！`);
            
            // 移除对话框
            dialog.remove();
        });
        
        // 取消按钮点击事件
        dialog.find('#cancel-settings').click(function() {
            dialog.remove();
        });
        
        // 点击对话框外部关闭
        dialog.click(function(e) {
            if (e.target === dialog[0]) {
                dialog.remove();
            }
        });
    }
    
    // 处理玩家卡片点击
    function handlePlayerClick(playerId) {
        // 上帝模式下的特殊处理
        if (gameState.isGodMode) {
            // 根据当前游戏阶段执行不同操作
            switch(gameState.phase) {
                case '夜晚':
                    // 上帝模式下可以直接处理夜晚操作
                    handleNightActions(playerId);
                    break;
                case '投票阶段':
                    // 上帝模式下可以直接处理投票
                    handleVote(playerId);
                    break;
                default:
                    // 其他阶段点击玩家卡片可以显示信息（包括身份）
                    const player = getPlayerById(playerId);
                    alert(`${player.name}\n状态: ${player.status}\n身份: ${player.role} ${roles[player.role].icon}\n阵营: ${roles[player.role].team}`);
            }
        } else {
            // 普通玩家模式
            // 根据当前游戏阶段执行不同操作
            switch(gameState.phase) {
                case '夜晚':
                    handleNightActions(playerId);
                    break;
                case '投票阶段':
                    handleVote(playerId);
                    break;
                default:
                    // 其他阶段点击玩家卡片可以显示信息
                    showPlayerInfo(playerId);
            }
        }
    }
    
    // 处理夜晚操作
    function handleNightActions(playerId) {
        // 根据不同夜晚子阶段执行相应操作
        switch(gameState.nightSubPhase) {
            case '狼人行动':
                // 初始化狼人行动状态
                if (!gameState.werewolfActions) {
                    gameState.werewolfActions = {}
                    const aliveWerewolves = gameState.werewolves.filter(id => !gameState.deadPlayers.includes(id));
                    aliveWerewolves.forEach(id => {
                        gameState.werewolfActions[id] = false; // false 表示尚未执行行动
                    });
                    gameState.werewolfTarget = null; // 存储最终目标
                    gameState.werewolfTargetVotes = {}; // 存储每个狼人的投票
                }
                
                // 上帝模式下直接执行操作
                if (gameState.isGodMode) {
                    // 遍历所有存活的玩家，获取其中的狼人
                    const aliveWerewolves = gameState.werewolves.filter(id => !gameState.deadPlayers.includes(id));
                    
                    // 检查是否所有狼人都已执行行动
                    const allActed = aliveWerewolves.every(id => gameState.werewolfActions[id]);
                    
                    // 如果未全部执行，让未执行的狼人执行行动
                    if (!allActed) {
                        // 获取第一个未执行行动的狼人
                        const currentWolfId = aliveWerewolves.find(id => !gameState.werewolfActions[id]);
                        
                        // 标记该狼人已执行行动
                        gameState.werewolfActions[currentWolfId] = true;
                        
                        // 存储每个狼人选择的目标
                        gameState.werewolfTargetVotes[currentWolfId] = playerId;
                        
                        // 添加消息和高光效果
                        addMessage('狼人', `${getPlayerById(currentWolfId).name} 选择了 ${getPlayerById(playerId).name} 作为今晚的目标。`);
                        highlightPlayer(currentWolfId, 'highlight-action');
                        
                        // 检查是否所有狼人都已执行行动
                        const nowAllActed = aliveWerewolves.every(id => gameState.werewolfActions[id]);
                        if (nowAllActed) {
                            addMessage('系统', '所有狼人已完成行动，确定今晚的目标。');
                            // 这里可以执行狼人杀人的最终操作
                        }
                    }
                } else if (gameState.currentRole === '狼人') {
                    // 普通玩家模式 - 用户点击选择目标
                    addMessage('狼人', `狼人选择了 ${getPlayerById(playerId).name} 作为今晚的目标。`);
                    highlightPlayer(gameState.currentPlayer.id, 'highlight-action');
                }
                break;
            case '预言家行动':
                // 上帝模式下直接执行操作
                if (gameState.isGodMode) {
                    // 预言家查验
                    const targetPlayer = getPlayerById(playerId);
                    const isWerewolf = gameState.werewolves.includes(playerId);
                    addMessage('预言家', `预言家查验了 ${targetPlayer.name}，结果是${isWerewolf ? '狼人' : '好人'}。`);
                    // 为执行行动的玩家添加高光效果（使用预言家）
                    if (gameState.prophet && !gameState.deadPlayers.includes(gameState.prophet)) {
                        highlightPlayer(gameState.prophet, 'highlight-action');
                    }
                } else if (gameState.currentRole === '预言家') {
                    // 普通玩家模式
                    const targetPlayer = getPlayerById(playerId);
                    const isWerewolf = gameState.werewolves.includes(playerId);
                    addMessage('预言家', `预言家查验了 ${targetPlayer.name}，结果是${isWerewolf ? '狼人' : '好人'}。`);
                    highlightPlayer(gameState.currentPlayer.id, 'highlight-action');
                }
                break;
            case '女巫行动':
                // 上帝模式下根据当前阶段执行操作
                if (gameState.isGodMode) {
                    handleWitchGodAction(playerId);
                } else if (gameState.currentRole === '女巫') {
                    // 普通玩家模式
                    handleWitchPlayerAction(playerId);
                }
                break;
            case '猎人行动':
                // 上帝模式下直接执行操作
                if (gameState.isGodMode) {
                    // 猎人的特殊技能通常是被动触发的，但这里为了演示保留
                    addMessage('猎人', `猎人选择了目标 ${getPlayerById(playerId).name}。`);
                    // 为执行行动的玩家添加高光效果（使用猎人）
                    if (gameState.hunter && !gameState.deadPlayers.includes(gameState.hunter)) {
                        highlightPlayer(gameState.hunter, 'highlight-action');
                    }
                } else if (gameState.currentRole === '猎人') {
                    // 普通玩家模式
                    addMessage('猎人', `猎人选择了目标 ${getPlayerById(playerId).name}。`);
                    highlightPlayer(gameState.currentPlayer.id, 'highlight-action');
                }
                break;
        }
    }
    
    // 处理投票
    function handleVote(playerId) {
        // 上帝模式下直接记录投票（跳过验证，由上帝控制）
        if (gameState.isGodMode) {
            // 选择一个未投票的存活玩家来投票
            const alivePlayers = gameState.players.filter(p => p.status === '存活').map(p => p.id);
            const unvotedPlayers = alivePlayers.filter(id => !Object.keys(gameState.votes).includes(id.toString()));
            
            if (unvotedPlayers.length > 0) {
                const voterId = unvotedPlayers[0];
                gameState.votes[voterId] = playerId;
                
                const voter = getPlayerById(voterId);
                addMessage(voter.name, `投票给了 ${getPlayerById(playerId).name}`);
                
                // 为投票的玩家添加高光效果
                highlightPlayer(voterId, 'highlight-vote');
                
                // 检查是否所有玩家都已投票
                if (Object.keys(gameState.votes).length === gameState.players.filter(p => p.status === '存活').length) {
                    setTimeout(() => {
                        countVotes();
                    }, 1000);
                }
            }
        } else {
            // 普通玩家模式
            const voter = gameState.currentPlayer;
            gameState.votes[voter.id] = playerId;
            
            addMessage(voter.name, `投票给了 ${getPlayerById(playerId).name}`);
            
            // 为投票的玩家添加高光效果
            highlightPlayer(voter.id, 'highlight-vote');
            
            // 检查是否所有玩家都已投票
            if (Object.keys(gameState.votes).length === gameState.players.filter(p => p.status === '存活').length) {
                setTimeout(() => {
                    countVotes();
                }, 1000);
            }
        }
    }
    
    // 计票
    function countVotes() {
        const voteCount = {};
        
        // 统计票数
        for (const [voterId, targetId] of Object.entries(gameState.votes)) {
            if (!voteCount[targetId]) {
                voteCount[targetId] = 0;
            }
            voteCount[targetId]++;
        }
        
        // 找出得票最多的玩家
        let maxVotes = 0;
        let votedPlayerId = null;
        
        for (const [playerId, votes] of Object.entries(voteCount)) {
            if (votes > maxVotes) {
                maxVotes = votes;
                votedPlayerId = parseInt(playerId);
            }
        }
        
        // 淘汰玩家
        if (votedPlayerId) {
            const votedPlayer = getPlayerById(votedPlayerId);
            gameState.deadPlayers.push(votedPlayerId);
            votedPlayer.status = '死亡';
            
            addMessage('系统', `${votedPlayer.name} 被投票出局！`);
            
            // 检查游戏是否结束
            if (checkGameEnd()) {
                endGame();
                return;
            }
        }
        
        // 进入夜晚
        enterNightPhase();
    }
    
    // 显示玩家信息
    function showPlayerInfo(playerId) {
        const player = getPlayerById(playerId);
        
        // 填充弹窗内容
        $('#player-info-name').text(player.name);
        $('#player-info-status').text(`状态: ${player.status}`);
        
        // 添加AI设置信息（如果有）
        const aiSettings = gameState.playerAISettings[playerId];
        if (aiSettings && aiSettings.model) {
            $('#player-info-ai').text(`AI模型: ${aiSettings.model}`);
            $('#player-info-ai').show();
        } else {
            $('#player-info-ai').hide();
        }
        
        // 添加身份信息（如果是上帝模式）
        if (gameState.isGodMode) {
            $('#player-info-role').text(`身份: ${player.role} ${roles[player.role].icon}`);
            $('#player-info-team').text(`阵营: ${roles[player.role].team}`);
            $('#player-info-role').show();
            $('#player-info-team').show();
            
            // 如果是女巫，显示药水状态
            if (player.role === '女巫') {
                $('#player-info-potions').text(
                    `解药状态: ${gameState.witchPotions.hasAntidote ? '可用' : '已使用'} | 
                     毒药状态: ${gameState.witchPotions.hasPoison ? '可用' : '已使用'}`
                );
                $('#player-info-potions').show();
            } else {
                $('#player-info-potions').hide();
            }
        } else {
            $('#player-info-role').hide();
            $('#player-info-team').hide();
            $('#player-info-potions').hide();
        }
        
        // 显示弹窗和遮罩
        $('#player-info-modal').addClass('active');
        $('#overlay').addClass('active');
    }
    
    // 关闭玩家信息弹窗
    $('#close-player-info').click(function() {
        $('#player-info-modal').removeClass('active');
        $('#overlay').removeClass('active');
    });
    
    // 点击遮罩层关闭弹窗
    $('#overlay').click(function(e) {
        // 只有当点击的是遮罩层本身而不是弹窗内容时才关闭
        if (e.target === this) {
            $('#player-info-modal').removeClass('active');
            $('#role-info').removeClass('active');
            $('#overlay').removeClass('active');
        }
    });
    
    // 根据ID获取玩家
    function getPlayerById(id) {
        return gameState.players.find(p => p.id === id);
    }
    
    // 获取当前行动玩家的信息
    function getCurrentActionPlayerInfo() {
        // 初始化结果对象
        const result = {
            player: null,
            phase: gameState.phase,
            subPhase: null,
            actionType: null,
            canAct: false,
            roleInfo: null
        };
        
        // 根据游戏阶段获取子阶段信息
        if (gameState.phase === '夜晚') {
            result.subPhase = gameState.nightSubPhase;
        } else if (gameState.phase === '白天') {
            result.subPhase = gameState.daySubPhase;
        }
        
        // 根据阶段和子阶段确定当前行动玩家
        if (gameState.phase === '夜晚' && gameState.nightSubPhase) {
            // 夜晚不同子阶段的行动玩家
            switch(gameState.nightSubPhase) {
                case '狼人行动':
                    // 获取所有存活的狼人
                    const aliveWerewolves = gameState.werewolves
                        .filter(id => !gameState.deadPlayers.includes(id))
                        .map(id => getPlayerById(id));
                    
                    if (aliveWerewolves.length > 0) {
                        // 上帝模式下可能有多个行动玩家，这里返回第一个
                        // 实际游戏中狼人是集体行动的
                        result.player = aliveWerewolves[0];
                        result.actionType = '狼人杀人';
                        result.canAct = true;
                        result.roleInfo = roles['狼人'];
                    }
                    break;
                    
                case '预言家行动':
                    // 获取存活的预言家
                    if (gameState.prophet && !gameState.deadPlayers.includes(gameState.prophet)) {
                        result.player = getPlayerById(gameState.prophet);
                        result.actionType = '预言家查验';
                        result.canAct = true;
                        result.roleInfo = roles['预言家'];
                    }
                    break;
                    
                case '女巫行动':
                    // 获取存活的女巫
                    if (gameState.witch && !gameState.deadPlayers.includes(gameState.witch)) {
                        result.player = getPlayerById(gameState.witch);
                        result.actionType = '女巫使用药水';
                        result.canAct = true;
                        result.roleInfo = roles['女巫'];
                    }
                    break;
                    
                case '猎人行动':
                    // 获取存活的猎人
                    if (gameState.hunter && !gameState.deadPlayers.includes(gameState.hunter)) {
                        result.player = getPlayerById(gameState.hunter);
                        result.actionType = '猎人开枪';
                        result.canAct = true;
                        result.roleInfo = roles['猎人'];
                    }
                    break;
            }
        } else if (gameState.phase === '投票阶段') {
            // 投票阶段，当前玩家是正在投票的玩家
            if (gameState.currentPlayer && !gameState.deadPlayers.includes(gameState.currentPlayer.id)) {
                result.player = gameState.currentPlayer;
                result.actionType = '投票';
                result.canAct = true;
                result.roleInfo = roles[gameState.currentRole || '村民'];
            }
        } else if (gameState.phase === '白天' && gameState.daySubPhase === '玩家发言') {
            // 白天发言阶段
            if (gameState.currentPlayer && !gameState.deadPlayers.includes(gameState.currentPlayer.id)) {
                result.player = gameState.currentPlayer;
                result.actionType = '发言';
                result.canAct = true;
                result.roleInfo = roles[gameState.currentRole || '村民'];
            }
        }
        
        // 兼容游戏中可能已设置的currentActionPlayer
        if (!result.player && gameState.currentActionPlayer) {
            result.player = gameState.currentActionPlayer;
            result.canAct = true;
        }
        
        return result;
    }
    
    // 移除所有玩家卡片的高光效果
    function removeAllHighlights() {
        $('.player-card').removeClass('highlight-action highlight-speak highlight-vote');
    }
    
    // 为指定玩家添加高光效果
    function highlightPlayer(playerId, highlightType) {
        // 先移除所有高光
        removeAllHighlights();
        
        // 为指定玩家添加高光
        $(`.player-card[data-id="${playerId}"]`).addClass(highlightType);
        
        // 3秒后自动移除高光
        setTimeout(() => {
            $(`.player-card[data-id="${playerId}"]`).removeClass(highlightType);
        }, 3000);
    }
    
    // 开始游戏
    function startGame() {
        if (gameState.gameStarted) return;
        
        gameState.gameStarted = true;
        
        // 初始化玩家
        initPlayers();
        renderPlayers();
        
        // 显示当前玩家角色（仅普通玩家）
        if (!gameState.isGodMode) {
            showRoleInfo();
        }
        
        // 更新游戏阶段
        gameState.phase = '夜晚';
        updatePhaseIndicator();
        
        // 更新按钮状态
        $('#start-game').addClass('btn-disabled');
        $('#next-phase').removeClass('btn-disabled');
        
        // 初始化按钮文本
        updateNextPhaseButton();
        
        // 上帝模式下的特殊提示
        if (gameState.isGodMode) {
            addMessage('系统', '您已以上帝玩家身份开始游戏，可以看到所有玩家的身份！');
        } else {
            addMessage('系统', '游戏开始了！天黑请闭眼...');
        }
    }
    
    // 显示角色信息（仅普通玩家）
    function showRoleInfo() {
        if (gameState.isGodMode) return; // 上帝玩家不需要显示角色信息
        
        const roleInfo = roles[gameState.currentRole];
        
        $('#role-icon').text(roleInfo.icon);
        $('#role-title').text(gameState.currentRole);
        $('#role-description').text(roleInfo.description);
        
        $('#role-info').addClass('active');
        $('#overlay').addClass('active');
    }
    
    // 进入白天阶段
    function enterDayPhase() {
        gameState.phase = '白天';
        gameState.dayCount++;
        gameState.nightSubPhase = null; // 重置夜晚子阶段
        
        $('body').removeClass('night-mode');
        
        // 开始白天阶段流程
        startDaySequence();
        
        // 开启投票按钮
        $('#vote-button').removeClass('btn-disabled');
    }
    
    // 开始白天阶段序列
    function startDaySequence() {
        // 1. 天亮
        gameState.daySubPhase = '天亮';
        updatePhaseIndicator();
        
        // 处理预死亡状态的玩家（如果女巫没有使用解药）
        if (gameState.pendingDeathPlayer) {
            const pendingPlayer = getPlayerById(gameState.pendingDeathPlayer);
            
            // 将预死亡玩家标记为死亡
            pendingPlayer.status = '死亡';
            gameState.deadPlayers.push(gameState.pendingDeathPlayer);
            
            // 移除预死亡状态标记
            $(`#player-${gameState.pendingDeathPlayer}`).removeClass('pending-death');
            
            // 更新UI以反映玩家死亡
            renderPlayers();
            
            // 宣布夜晚死亡情况
            addMessage('系统', `天亮了！${pendingPlayer.name} 昨晚被狼人杀死了。`);
            
            // 清除预死亡状态
            gameState.pendingDeathPlayer = null;
        } else if (gameState.deadPlayers.length > 0) {
            // 处理毒药或其他原因导致的死亡
            const lastDeadPlayer = getPlayerById(gameState.deadPlayers[gameState.deadPlayers.length - 1]);
            addMessage('系统', `天亮了！${lastDeadPlayer.name} 昨晚死亡了。`);
        } else {
            addMessage('系统', '天亮了！昨晚是平安夜。');
        }
        
        // 移除自动计时器，由用户点击按钮手动控制
    }
    
    // 玩家发言阶段
    function enterSpeakPhase() {
        gameState.daySubPhase = '玩家发言';
        updatePhaseIndicator();
        
        addMessage('系统', '现在进入讨论阶段，请玩家们发言。');
    }
    
    // 进入夜晚阶段
    function enterNightPhase() {
        gameState.phase = '夜晚';
        gameState.nightCount++;
        gameState.daySubPhase = null; // 重置白天子阶段
        
        $('body').addClass('night-mode');
        
        // 重置投票
        gameState.votes = {};
        
        // 开始夜晚阶段流程
        startNightSequence();
        
        // 关闭投票按钮
        $('#vote-button').addClass('btn-disabled');
    }
    
    // 开始夜晚阶段序列
    function startNightSequence() {
        // 1. 天黑请闭眼
        gameState.nightSubPhase = '天黑请闭眼';
        updatePhaseIndicator();
        addMessage('系统', '天黑请闭眼...');
        
        // 移除自动计时器，由用户点击按钮手动控制
    }
    
    // 狼人行动阶段
    function enterWerewolfActionPhase() {
        gameState.nightSubPhase = '狼人行动';
        updatePhaseIndicator();
        
        // 重置狼人行动状态
        gameState.werewolfActions = {};
        gameState.werewolfTargetVotes = {};
        
        // 找到存活的狼人
        const aliveWerewolves = gameState.werewolves.filter(id => !gameState.deadPlayers.includes(id));
        
        if (aliveWerewolves.length > 0) {
            // 设置当前行动的狼人
            gameState.currentActionPlayer = getPlayerById(aliveWerewolves[0]);
            // addMessage('系统', '狼人请睁眼，选择要杀害的玩家...');
            
            // 调用AI来选择杀人目标
            callAIForWolfKill();
        }
        
        // 移除自动计时器，由用户点击按钮手动控制
    }
    
    // 预言家行动阶段
    function enterProphetActionPhase() {
        gameState.nightSubPhase = '预言家行动';
        updatePhaseIndicator();
        
        // 检查预言家是否存活
        const prophet = getPlayerById(gameState.prophet);
        if (prophet && prophet.status === '存活') {
            gameState.currentActionPlayer = prophet;
            addMessage('系统', '预言家请睁眼，选择要查验的玩家...');
        }
        
        // 移除自动计时器，由用户点击按钮手动控制
    }
    
    // 女巫行动阶段
    function enterWitchActionPhase() {
        gameState.nightSubPhase = '女巫行动';
        // 初始化女巫行动状态
        if (!gameState.witchActionState) {
            gameState.witchActionState = {
                step: 'antidote', // antidote: 解药阶段, poison: 毒药阶段, complete: 完成
                hasUsedAntidote: false,
                hasUsedPoison: false,
                savedPlayer: null,
                poisonedPlayer: null
            };
        } else {
            // 重置当前阶段
            gameState.witchActionState.step = 'antidote';
        }
        updatePhaseIndicator();
        
        // 检查女巫是否存活
        const witch = getPlayerById(gameState.witch);
        if (witch && witch.status === '存活') {
            gameState.currentActionPlayer = witch;
            addMessage('系统', '女巫请睁眼！');
            
            // 首先进入解药阶段
            enterAntidotePhase();
        }
        
        // 移除自动计时器，由用户点击按钮手动控制
    }
    
    // 解药阶段
    function enterAntidotePhase() {
        gameState.witchActionState.step = 'antidote';
        
        // 检查是否有解药可用以及是否有预死亡状态的玩家
        if (gameState.witchPotions.hasAntidote && gameState.pendingDeathPlayer) {
            addMessage('系统', '你有一瓶解药，可以选择救活今晚将被狼人杀死的玩家，或者选择不使用解药。');
            // 上帝模式下显示可救的玩家
            if (gameState.isGodMode) {
                const pendingPlayer = getPlayerById(gameState.pendingDeathPlayer);
                addMessage('系统', `今晚 ${pendingPlayer.name} 将被狼人杀死，你要使用解药救活他吗？`);
            }
        } else {
            // 解药已用完或无预死亡状态玩家，直接进入毒药阶段
            addMessage('系统', '你没有解药可用或今晚无人会被狼人杀死，进入毒药阶段。');
            setTimeout(enterPoisonPhase, 1000);
        }
    }
    
    // 毒药阶段
    function enterPoisonPhase() {
        gameState.witchActionState.step = 'poison';
        
        // 检查是否有毒药可用
        if (gameState.witchPotions.hasPoison) {
            addMessage('系统', '你有一瓶毒药，可以选择毒死任意一名存活的玩家，或者选择不使用毒药。');
            // 上帝模式下的提示
            if (gameState.isGodMode) {
                addMessage('系统', '点击玩家卡片选择要毒死的目标，或点击"下一阶段"跳过。');
            }
        } else {
            // 毒药已用完，结束女巫行动
            addMessage('系统', '你没有毒药可用，女巫行动结束。');
            gameState.witchActionState.step = 'complete';
        }
    }
    
    // 处理普通玩家模式下的女巫行动
    function handleWitchPlayerAction(playerId) {
        const witchActionState = gameState.witchActionState;
        
        // 解药阶段
        if (witchActionState.step === 'antidote') {
            // 检查是否有解药可用
            if (gameState.witchPotions.hasAntidote) {
                // 普通玩家模式下，系统会告知女巫今晚是否有人将被狼人杀死
                const hasPendingDeathPlayer = confirm('今晚有人将被狼人杀死，是否使用解药？');
                
                if (hasPendingDeathPlayer && gameState.pendingDeathPlayer) {
                    // 使用解药
                    witchActionState.hasUsedAntidote = true;
                    gameState.witchPotions.hasAntidote = false;
                    
                    // 救活预死亡状态的玩家
                    witchActionState.savedPlayer = gameState.pendingDeathPlayer;
                    const savedPlayer = getPlayerById(gameState.pendingDeathPlayer);
                    
                    addMessage('女巫', `你使用了解药，救活了 ${savedPlayer.name}。`);
                    highlightPlayer(gameState.currentPlayer.id, 'highlight-action');
                    
                    // 移除预死亡状态标记
                    $(`#player-${gameState.pendingDeathPlayer}`).removeClass('pending-death');
                    
                    // 清除预死亡状态
                    gameState.pendingDeathPlayer = null;
                } else {
                    addMessage('女巫', '你选择不使用解药。');
                }
                
                // 进入毒药阶段
                setTimeout(enterPoisonPhase, 1000);
            } else {
                // 直接进入毒药阶段
                enterPoisonPhase();
            }
        }
        // 毒药阶段
        else if (witchActionState.step === 'poison') {
            // 检查是否有毒药可用
            if (gameState.witchPotions.hasPoison) {
                const usePoison = confirm(`是否使用毒药毒死 ${getPlayerById(playerId).name}？`);
                
                if (usePoison) {
                    // 使用毒药
                    witchActionState.hasUsedPoison = true;
                    witchActionState.poisonedPlayer = playerId;
                    gameState.witchPotions.hasPoison = false;
                    
                    // 记录被毒死的玩家，稍后处理
                    gameState.poisonedPlayer = playerId;
                    
                    addMessage('女巫', `你使用了毒药，选择了 ${getPlayerById(playerId).name} 作为目标。`);
                    highlightPlayer(gameState.currentPlayer.id, 'highlight-action');
                } else {
                    addMessage('女巫', '你选择不使用毒药。');
                }
                
                // 完成女巫行动
                witchActionState.step = 'complete';
                addMessage('系统', '你的行动已完成，请等待天亮。');
            }
        }
    }
    
    // 处理上帝模式下的女巫行动
    function handleWitchGodAction(playerId) {
        const witchActionState = gameState.witchActionState;
        
        // 解药阶段
        if (witchActionState.step === 'antidote') {
            // 检查是否有解药可用
            if (gameState.witchPotions.hasAntidote && gameState.pendingDeathPlayer) {
                const pendingPlayer = getPlayerById(gameState.pendingDeathPlayer);
                const useAntidote = confirm(`是否使用解药救活今晚将被狼人杀死的玩家 ${pendingPlayer.name}？`);
                
                if (useAntidote) {
                    // 救活预死亡状态的玩家
                    witchActionState.hasUsedAntidote = true;
                    witchActionState.savedPlayer = gameState.pendingDeathPlayer;
                    gameState.witchPotions.hasAntidote = false;
                    
                    addMessage('女巫', `女巫使用了解药，救活了 ${pendingPlayer.name}。`);
                    
                    // 为女巫添加高光效果
                    highlightPlayer(gameState.witch, 'highlight-action');
                    
                    // 移除预死亡状态标记
                    $(`#player-${gameState.pendingDeathPlayer}`).removeClass('pending-death');
                    
                    // 清除预死亡状态
                    gameState.pendingDeathPlayer = null;
                } else {
                    addMessage('女巫', '女巫选择不使用解药。');
                }
                
                // 进入毒药阶段
                setTimeout(enterPoisonPhase, 1000);
            } else {
                // 直接进入毒药阶段
                enterPoisonPhase();
            }
        }
        // 毒药阶段
        else if (witchActionState.step === 'poison') {
            // 检查是否有毒药可用
            if (gameState.witchPotions.hasPoison) {
                const usePoison = confirm(`是否使用毒药毒死 ${getPlayerById(playerId).name}？`);
                
                if (usePoison) {
                    // 使用毒药
                    witchActionState.hasUsedPoison = true;
                    witchActionState.poisonedPlayer = playerId;
                    gameState.witchPotions.hasPoison = false;
                    
                    // 记录被毒死的玩家，稍后处理
                    gameState.poisonedPlayer = playerId;
                    
                    addMessage('女巫', `女巫使用了毒药，选择了 ${getPlayerById(playerId).name} 作为目标。`);
                    
                    // 为女巫添加高光效果
                    highlightPlayer(gameState.witch, 'highlight-action');
                } else {
                    addMessage('女巫', '女巫选择不使用毒药。');
                }
                
                // 完成女巫行动
                witchActionState.step = 'complete';
                addMessage('系统', '女巫行动完成。');
            }
        }
    }
    
    // 猎人行动阶段
    function enterHunterActionPhase() {
        gameState.nightSubPhase = '猎人行动';
        updatePhaseIndicator();
        
        // 检查猎人是否存活
        const hunter = getPlayerById(gameState.hunter);
        if (hunter && hunter.status === '存活') {
            gameState.currentActionPlayer = hunter;
            addMessage('系统', '猎人请保持警惕，你的枪已上膛...');
        }
        
        // 移除自动计时器，由用户点击按钮手动控制
    }
    
    // 进入投票阶段
    function enterVotePhase() {
        gameState.phase = '投票阶段';
        gameState.daySubPhase = null; // 重置白天子阶段
        updatePhaseIndicator();
        
        addMessage('系统', '讨论时间结束，现在开始投票！');
    }
    
    // 更新阶段指示器
    function updatePhaseIndicator() {
        let phaseText = gameState.phase;
        
        if (gameState.phase === '白天') {
            phaseText = `第 ${gameState.dayCount} 天`;
            if (gameState.daySubPhase) {
                phaseText += ` - ${gameState.daySubPhase}`;
            }
        } else if (gameState.phase === '夜晚') {
            phaseText = `第 ${gameState.nightCount} 晚`;
            if (gameState.nightSubPhase) {
                phaseText += ` - ${gameState.nightSubPhase}`;
            }
        }
        
        $('#phase-indicator').text(phaseText);
        
        // 同时更新下一阶段按钮文本
        updateNextPhaseButton();
    }
    
    // 更新下一阶段按钮文本
    function updateNextPhaseButton() {
        let buttonText = '下一阶段';
        
        // 根据当前游戏阶段和子阶段决定按钮文本
        if (gameState.phase === '准备阶段') {
            buttonText = '开始游戏';
        } else if (gameState.phase === '夜晚') {
            if (!gameState.nightSubPhase || gameState.nightSubPhase === '天黑请闭眼') {
                buttonText = '狼人行动阶段';
            } else if (gameState.nightSubPhase === '狼人行动') {
                buttonText = '预言家行动阶段';
            } else if (gameState.nightSubPhase === '预言家行动') {
                buttonText = '女巫行动阶段';
            } else if (gameState.nightSubPhase === '女巫行动') {
                // 检查女巫行动是否完成
                if (gameState.witchActionState && gameState.witchActionState.step === 'complete') {
                    buttonText = '猎人行动阶段';
                } else {
                    buttonText = '完成女巫行动';
                }
            } else if (gameState.nightSubPhase === '猎人行动') {
                buttonText = '进入白天';
            }
        } else if (gameState.phase === '白天') {
            if (!gameState.daySubPhase) {
                buttonText = '天亮';
            } else if (gameState.daySubPhase === '天亮') {
                buttonText = '玩家发言阶段';
            } else if (gameState.daySubPhase === '玩家发言') {
                buttonText = '投票阶段';
            }
        } else if (gameState.phase === '投票阶段') {
            buttonText = '进入夜晚';
        } else if (gameState.phase === '结束') {
            buttonText = '游戏结束';
        }
        
        $('#next-phase').text(buttonText);
    }
    
    // 添加聊天消息
    function addMessage(sender, content) {
        // 创建消息容器
        const messageContainer = $('<div>').addClass('message-container');
        
        // 创建消息内容区
        const messageClass = sender === '系统' ? 'message system-message' : 'message user-message';
        const message = $('<div>').addClass(messageClass);
        
        if (sender === '系统') {
            // 系统消息样式
            message.append($('<span>').addClass('sender').text(sender));
            message.append(document.createTextNode(content));
        } else {
            // 查找玩家信息
            let playerId = null;
            let playerRole = null;
            let playerIcon = null;
            let playerNumber = null;
            
            // 查找对应的玩家
            for (let i = 0; i < gameState.players.length; i++) {
                if (gameState.players[i].name === sender) {
                    playerId = gameState.players[i].id;
                    playerRole = gameState.players[i].role;
                    playerNumber = playerId; // 假设玩家ID就是编号
                    break;
                }
            }
            
            // 获取玩家角色图标
            if (playerRole && roles[playerRole]) {
                playerIcon = roles[playerRole].icon || '👤';
            } else {
                playerIcon = '👤';
            }
            
            // 创建玩家信息区域
            const playerInfo = $('<div>').addClass('player-info-header');
            playerInfo.append($('<span>').addClass('player-icon').text(playerIcon));
            playerInfo.append($('<span>').addClass('player-number').text(`[${playerNumber}]`));
            playerInfo.append($('<span>').addClass('player-name').text(sender));
            if (playerRole) {
                playerInfo.append($('<span>').addClass('player-role-name').text(`(${playerRole})`));
            }
            
            // 添加到消息中
            message.append(playerInfo);
            message.append($('<div>').addClass('message-content').text(content));
        }
        
        // 将消息添加到容器
        messageContainer.append(message);
        
        // 添加到聊天区域
        $('#chat-messages').append(messageContainer);
        
        // 滚动到底部
        const chatMessages = $('#chat-messages');
        chatMessages.scrollTop(chatMessages[0].scrollHeight);
    }
    
    // 检查游戏是否结束
    function checkGameEnd() {
        // 狼人全部死亡，好人胜利
        const aliveWerewolves = gameState.werewolves.filter(id => !gameState.deadPlayers.includes(id));
        if (aliveWerewolves.length === 0) {
            gameState.winner = '好人';
            return true;
        }
        
        // 狼人数量大于等于好人数量，狼人胜利
        const aliveGoodPlayers = gameState.players.filter(p => 
            p.status === '存活' && !gameState.werewolves.includes(p.id)
        ).length;
        
        if (aliveWerewolves.length >= aliveGoodPlayers) {
            gameState.winner = '狼人';
            return true;
        }
        
        return false;
    }
    
    // 结束游戏
    function endGame() {
        gameState.phase = '结束';
        updatePhaseIndicator();
        
        addMessage('系统', `游戏结束！${gameState.winner}阵营获得胜利！`);
        
        // 显示所有玩家的角色
        gameState.players.forEach(player => {
            addMessage('系统', `${player.name} 的身份是: ${player.role}`);
        });
        
        // 禁用所有按钮
        $('.btn').addClass('btn-disabled');
    }
    
    // 调用AI选择狼人杀人目标
    function callAIForWolfKill(specificWolfId) {
        // 找到存活的狼人
        const aliveWerewolves = gameState.werewolves.filter(id => !gameState.deadPlayers.includes(id));
        
        if (aliveWerewolves.length === 0) return;
        
        // 获取当前行动的狼人，如果有指定ID则使用指定的狼人
        const currentWolf = specificWolfId ? getPlayerById(specificWolfId) : getPlayerById(aliveWerewolves[0]);
        
        // 确保狼人对话历史列表存在
        if (!window.werewolfDialogues) {
            window.werewolfDialogues = [];
        }
        
        // 准备游戏状态信息
        let gameStatus = `当前是第${gameState.dayCount}天，是夜晚状态；您的身份是狼人，您的编号是${currentWolf.id}，您存活；`;
        
        // 添加狼队友信息
        const wolfTeammates = aliveWerewolves.filter(id => id !== currentWolf.id);
        if (wolfTeammates.length > 0) {
            gameStatus += `您的队友狼人是${wolfTeammates.join('、')}；`;
        }
        
        // 添加之前的对话上下文
        if (gameState.lastWolfDialogueIndex !== undefined && gameState.lastWolfDialogueIndex < window.werewolfDialogues.length) {
            gameStatus += '\n狼人团队的对话如下：';
            // 获取从lastWolfDialogueIndex开始的对话
            const recentDialogues = window.werewolfDialogues.slice(gameState.lastWolfDialogueIndex);
            // 格式化对话内容
            recentDialogues.forEach(dialogue => {
                const role = dialogue.role === 'system' ? '系统' : 
                            dialogue.role === 'user' ? '狼人' : 
                            dialogue.role === 'assistant' ? `狼人${dialogue.wolfId}` : dialogue.role;
                gameStatus += `\n${role}：${dialogue.content}`;
            });
        }
        
        // 添加存活玩家信息
        const alivePlayers = gameState.players
            .filter(id => !gameState.deadPlayers.includes(id) && id !== currentWolf.id)
            .filter(id => !wolfTeammates.includes(id));
        
        if (alivePlayers.length > 0) {
            gameStatus += '场上还存活的平民/神民：';
            alivePlayers.forEach((player, index) => {
                gameStatus += player.name;
                if (index < alivePlayers.length - 1) {
                    gameStatus += '、';
                }
            });
            gameStatus += '。';
        }
        
        // 更新AI对话的系统提示
        chatHistory.push({
            "role": "system",
            "content": getPrompt("lyc", currentWolf.id, gameStatus)
        });
        
        // 发送消息给AI，让它选择杀人目标
        const aiPrompt = "天黑请闭眼，狼人请睁眼，请问您要杀死的玩家是谁？";
        sendAIMessage(aiPrompt);
        
        // 将狼人相关的对话保存到狼人对话历史列表
        const systemPrompt = getPrompt("lyc", currentWolf.id, gameStatus);
        window.werewolfDialogues.push({
            "role": "system",
            "content": systemPrompt,
            "timestamp": new Date().toISOString(),
            "wolfId": currentWolf.id,
            "phase": gameState.phase,
            "nightSubPhase": gameState.nightSubPhase
        });
        werewolfDialogues.push({
            "role": "user",
            "content": aiPrompt,
            "timestamp": new Date().toISOString(),
            "wolfId": currentWolf.id,
            "phase": gameState.phase,
            "nightSubPhase": gameState.nightSubPhase
        });
    }
    
    // 处理狼人工具调用结果
    function processWolfKillResult(result) {
        try {
            // 解析狼人和目标信息
            const [wolfNo, targetNo] = result.split(':');
            
            if (wolfNo && targetNo) {
                const wolfPlayer = getPlayerById(wolfNo);
                const targetPlayer = getPlayerById(targetNo);
                
                if (wolfPlayer && targetPlayer) {
                    // 确保狼人目标投票对象存在
                    if (!gameState.werewolfTargetVotes) {
                        gameState.werewolfTargetVotes = {};
                    }
                    
                    // 确保狼人行动状态对象存在
                    if (!gameState.werewolfActions) {
                        gameState.werewolfActions = {};
                    }
                    
                    // 记录狼人选择的目标
                    gameState.werewolfTargetVotes[wolfNo] = targetNo;
                    
                    // 标记狼人已执行行动
                    gameState.werewolfActions[wolfNo] = true;
                    
                    // 添加消息和高光效果
                    addMessage('狼人', `${wolfPlayer.name} 选择了 ${targetPlayer.name} 作为今晚的目标。`);
                    highlightPlayer(wolfNo, 'highlight-action');
                    
                    // 获取存活的狼人
                    const aliveWerewolves = gameState.werewolves.filter(id => !gameState.deadPlayers.includes(id));
                    
                    // 检查是否所有狼人都已执行行动
                    const allActed = aliveWerewolves.every(id => gameState.werewolfActions[id]);
                    
                    if (allActed) {
                        addMessage('系统', '所有狼人已完成行动，确定今晚的目标。');
                        
                        // 统计每个玩家的得票数
                        const voteCounts = {};
                        for (const wolfId in gameState.werewolfTargetVotes) {
                            const targetId = gameState.werewolfTargetVotes[wolfId];
                            voteCounts[targetId] = (voteCounts[targetId] || 0) + 1;
                        }
                        
                        // 找到得票最多的玩家
                        let maxVotes = 0;
                        let targetId = null;
                        for (const playerId in voteCounts) {
                            if (voteCounts[playerId] > maxVotes) {
                                maxVotes = voteCounts[playerId];
                                targetId = playerId;
                            }
                        }
                        
                        // 设置最终目标
                        gameState.werewolfTarget = targetId;
                    } else {
                        // 查找下一个未行动的狼人
                        const nextWolfId = aliveWerewolves.find(id => !gameState.werewolfActions[id]);
                        
                        // 如果有未行动的狼人
                        if (nextWolfId) {
                            // 保存当前对话上下文索引，用于下一个狼人
                            gameState.lastWolfDialogueIndex = window.werewolfDialogues.length;
                            // 立即让下一个狼人参与对话，不使用异步
                            setTimeout(() => {
                                callAIForWolfKill(nextWolfId);
                            }, 500); // 稍微延迟一下，让UI有时间更新
                        }
                    }
                }
            }
        } catch (error) {
            console.error('处理狼人杀人结果失败:', error);
            // 在控制台显示详细错误信息，帮助调试
            console.log('当前gameState:', gameState);
            console.log('当前狼行动状态:', gameState.werewolfActions);
            console.log('当前狼人目标:', gameState.werewolfTargetVotes);
        }
    }
    
    // 重写wolf_kill函数，加入处理结果的逻辑
    const originalWolfKill = window.wolf_kill;
    window.wolf_kill = function(wolfNo, targetNo) {
        const result = originalWolfKill(wolfNo, targetNo);
        $(`#players-container > div:nth-child(${targetNo})`).click();
        // 异步处理结果，避免阻塞UI
        setTimeout(() => {
            processWolfKillResult(result);
        }, 100);
        return result;
    };
    
    // 事件监听
    $('#start-game').click(startGame);
    
    // 初始化按钮文本
    updateNextPhaseButton();
    
    $('#next-phase').click(function() {
        // 根据当前游戏阶段和子阶段决定下一步操作
        if (gameState.phase === '准备阶段') {
            // 游戏未开始，不执行任何操作
            return;
        } else if (gameState.phase === '夜晚') {
            // 夜晚阶段的子阶段切换
            if (!gameState.nightSubPhase || gameState.nightSubPhase === '天黑请闭眼') {
                enterWerewolfActionPhase();
            } else if (gameState.nightSubPhase === '狼人行动') {
                // 检查是否所有狼人都已完成行动
                if (gameState.werewolfActions) {
                    const aliveWerewolves = gameState.werewolves.filter(id => !gameState.deadPlayers.includes(id));
                    const allActed = aliveWerewolves.every(id => gameState.werewolfActions[id]);
                    
                    if (!allActed) {
                        // 未完成行动，提示用户
                        addMessage('系统', '还有狼人未完成选择，请确保所有狼人都选择目标后再进入下一阶段。');
                        return; // 阻止进入下一阶段
                    }
                    // 统计每个玩家的得票数
                    const voteCounts = {};
                    Object.values(gameState.werewolfTargetVotes).forEach(targetId => {
                        voteCounts[targetId] = (voteCounts[targetId] || 0) + 1;
                    });
                     
                    // 找出得票最高的玩家和得票数
                    let maxVotes = 0;
                    let topVotedPlayers = [];
                    
                    for (const [playerId, count] of Object.entries(voteCounts)) {
                        if (count > maxVotes) {
                            maxVotes = count;
                            topVotedPlayers = [parseInt(playerId)];
                        } else if (count === maxVotes) {
                            topVotedPlayers.push(parseInt(playerId));
                        }
                    }
                     
                    // 检查是否有唯一的最高得票玩家
                    if (topVotedPlayers.length === 1) {
                        // 有唯一最高得票玩家，设置预死亡状态
                        const pendingDeathId = topVotedPlayers[0];
                        gameState.pendingDeathPlayer = pendingDeathId;
                        gameState.werewolfTarget = pendingDeathId;
                        
                        // 标记该玩家为预死亡状态
                        const pendingPlayer = gameState.players.find(p => p.id === pendingDeathId);
                        addMessage('系统', `${pendingPlayer.name} 获得最多狼人投票，进入预死亡状态。女巫可以选择是否使用解药。`);
                        
                        // 为预死亡玩家添加特殊样式标记
                        $(`#player-${pendingDeathId}`).addClass('pending-death');
                    } else {
                        // 最高得票数相同的玩家有多个，需要狼人重新选择
                        addMessage('系统', '狼人选择出现平局，请重新进行选择。');
                        
                        // 重置狼人行动状态，让狼人重新选择
                        const aliveWerewolves = gameState.werewolves.filter(id => !gameState.deadPlayers.includes(id));
                        gameState.werewolfActions = {};
                        gameState.werewolfTargetVotes = {};
                        gameState.werewolfTarget = null;
                        
                        aliveWerewolves.forEach(id => {
                            gameState.werewolfActions[id] = false;
                        });
                        
                        return; // 阻止进入下一阶段
                    }
                }
                enterProphetActionPhase();
            } else if (gameState.nightSubPhase === '预言家行动') {
                enterWitchActionPhase();
            } else if (gameState.nightSubPhase === '女巫行动') {
                // 检查女巫行动是否完成
                if (gameState.witchActionState && gameState.witchActionState.step !== 'complete') {
                    // 如果解药阶段尚未完成，强制进入毒药阶段
                    if (gameState.witchActionState.step === 'antidote') {
                        addMessage('系统', '跳过解药阶段，进入毒药阶段。');
                        enterPoisonPhase();
                        return;
                    } else {
                        // 提示用户女巫行动尚未完成
                        addMessage('系统', '女巫行动尚未完成，请完成毒药阶段的选择。');
                        return;
                    }
                }
                enterHunterActionPhase();
            } else if (gameState.nightSubPhase === '猎人行动') {
                gameState.nightSubPhase = null;
                enterDayPhase();
            }
        } else if (gameState.phase === '白天') {
            // 白天阶段的子阶段切换
            if (!gameState.daySubPhase) {
                startDaySequence();
            } else if (gameState.daySubPhase === '天亮') {
                enterSpeakPhase();
            } else if (gameState.daySubPhase === '玩家发言') {
                enterVotePhase();
            }
        } else if (gameState.phase === '投票阶段') {
            // 投票阶段后进入夜晚
            enterNightPhase();
        } else if (gameState.phase === '结束') {
            // 游戏结束，不执行任何操作
            return;
        }
    });
    
    $('#vote-button').click(function() {
        if (gameState.phase === '白天') {
            enterVotePhase();
        }
    });
    
    $('#confirm-role').click(function() {
        $('#role-info').removeClass('active');
        $('#overlay').removeClass('active');
    });
    
    // 发送聊天消息
    $('#send-message').click(function() {
        const message = $('#message-input').val().trim();
        if (message) {
            if (gameState.isGodMode) {
                // 上帝模式下以系统名义发送消息
                addMessage('系统', message);
            } else if (gameState.currentPlayer) {
                // 普通玩家模式
                addMessage(gameState.currentPlayer.name, message);
                // 为当前发言的玩家添加高光效果
                highlightPlayer(gameState.currentPlayer.id, 'highlight-speak');
            }
            
            $('#message-input').val('');
        }
    })
    
    // 按Enter发送消息
    $('#message-input').keypress(function(e) {
        if (e.which === 13) {
            $('#send-message').click();
        }
    });
    
    // 游戏状态按钮点击事件
    $('#game-state').click(function() {
        // 收集游戏状态信息
        let stateInfo = `游戏阶段: ${gameState.phase}\n`;
        
        if (gameState.gameStarted) {
            // 统计存活玩家
            const alivePlayers = gameState.players.filter(p => p.status === '存活').length;
            const deadPlayers = gameState.deadPlayers.length;
            
            // 统计狼人数量
            const aliveWerewolves = gameState.werewolves.filter(id => !gameState.deadPlayers.includes(id)).length;
            
            stateInfo += `当前轮次: 第${gameState.dayCount}天/${gameState.nightCount}晚\n`;
            stateInfo += `存活玩家: ${alivePlayers}人\n`;
            stateInfo += `死亡玩家: ${deadPlayers}人\n`;
            stateInfo += `存活狼人: ${aliveWerewolves}人\n`;
            
            if (gameState.currentPlayer) {
                stateInfo += `当前玩家: ${gameState.currentPlayer.name} (${gameState.currentRole})\n`;
            }
        } else {
            stateInfo += '游戏尚未开始，请点击"开始游戏"按钮开始游戏';
        }
        
        // 显示游戏状态
        alert(stateInfo);
    });
    
    // 游戏是否结束按钮点击事件
    $('#is-end').click(function() {
        if (!gameState.gameStarted) {
            alert('游戏尚未开始，无法判断游戏是否结束');
            return;
        }
        
        const isEnd = checkGameEnd();
        
        if (isEnd) {
            alert(`游戏已经结束！${gameState.winner}阵营获得胜利！`);
            endGame(); // 调用结束游戏函数
        } else {
            // 计算剩余狼人数量
            const aliveWerewolves = gameState.werewolves.filter(id => !gameState.deadPlayers.includes(id)).length;
            // 计算剩余好人数量
            const aliveGoodPlayers = gameState.players.filter(p => 
                p.status === '存活' && !gameState.werewolves.includes(p.id)
            ).length;
            
            alert(`游戏尚未结束\n存活狼人: ${aliveWerewolves}人\n存活好人: ${aliveGoodPlayers}人`);
        }
    });
    
    // 初始化页面
    renderPlayers();
});